import {defineStore} from "pinia";
import {ref} from "vue";
import type {UserDetail, UserInfo} from "../utils/types/UserInfo";
import {Temp} from "../utils/Constant";
import {UserCheckState, UserDetailGet, UserInfoGet} from "../reqApi/UserApi";
import type {ResultInfo} from "../utils/types/ResultInfo";
import {StoreDiscovery} from "./discovery";

export const StoreLoginState = defineStore('isLogin', () => {
    const isLogin = ref(false)
    const Set = (islogin: boolean) => {
        isLogin.value = islogin
    }
    const Get = () => {
        let item = localStorage.getItem(Temp.Token);
        isLogin.value = item ? item.length >= 20 : false;
        if (!isLogin.value) {
            StoreUserDetail().Clean()
            StoreUserInfo().Clean()
            StoreDiscovery().Clean()
        } else {
            // UserCheckState().then(resp => {
            //     const result = resp.data as ResultInfo<any>
            //     console.log(result.msg)
            // })
        }
        return isLogin.value;
    }
    return {isLogin, Get, Set}
})

// useStore 可以是 useUser、useCart 之类的任何东西
// 第一个参数是应用程序中 store 的唯一 id
export const StoreUserDetail = defineStore('StoreUserDetail', () => {

    const userDetail = ref<UserDetail>()
    const Get = () => userDetail

    const Clean = () => userDetail.value = undefined

    const Flush = () => {
        UserDetailGet().then(resp => {
            const result = resp.data as ResultInfo<UserDetail>
            if (result.success) {
                userDetail.value = result.data
            } else {
                localStorage.setItem(Temp.Token, '')
            }
        })
    }
    return {userDetail, Flush, Get, Clean}

})
export const StoreUserInfo = defineStore('StoreUserInfo', () => {

    const userInfo = ref<UserInfo>()
    const Flush = () => {
        UserInfoGet().then(resp => {
            const result = resp.data as ResultInfo<UserInfo>
            if (result.success) {
                userInfo.value = result.data
            } else {
                localStorage.setItem(Temp.Token,'')
            }
        })
    }

    const Get = () => userInfo
    const Clean = () => userInfo.value = undefined
    return {userInfo, Flush, Get, Clean}

})
